from flask import g
import sqlite3
from contextlib import closing

def con_db(app):

    @app.before_request
    def before_request():
        g.db = connect_db(app)

    @app.teardown_request
    def teardown_request(exception):
        g.db.close()

def connect_db(app):
    return sqlite3.connect(app.config['DATABASE'])

def init_db(app):
    with closing(connect_db(app)) as db:
        with app.open_resource('schema.sql') as f:
            db.cursor().executescript(f.read().decode())
        db.commit()
